/*
 * @Description: 
 * @FilePath: /STM32/USER/api/rs485.h
 * @Author: Wei Zhou
 * @Github: https://github.com/zromyk
 * @Date: 2021-04-28 15:25:19
 * @LastEditors: Wei Zhou
 * @LastEditTime: 2021-04-28 21:50:03
 * @Copyright: Copyright  2017 muyiro. All rights reserved.
 */

#ifndef RS485_INIT_H
#define RS485_INIT_H

#include "my_include.h"
#include "tim.h"
#include "gpio.h"
#include "usart.h"
#include "delay.h"

/* Exported macro ------------------------------------------------------------*/

#define rs485_tx_mode(rs485)        do { \
                                        USART_ITConfig((rs485)->usart->USARTx, USART_IT_IDLE, DISABLE); \
                                        gpio_write((rs485)->pin_re, 1); \
                                    } while(0)
#define rs485_rx_mode(rs485)        do { \
                                        delay_us(10); \
                                        gpio_write((rs485)->pin_re, 0); \
                                        USART_ITConfig((rs485)->usart->USARTx, USART_IT_IDLE, ENABLE); \
                                    } while(0) 

/* Exported variable ---------------------------------------------------------*/

typedef struct
{
    USART_Dev   *usart;
    PIN_Dev     pin_re;
} rs485_dev;

/* initialize functions ----------------------------------------------------- */
/**
 * @brief  rs485 iniialize function.
 *         [eg.] rs485_init(&rs485, &usart1, PA0);
 * @param  *rs485:  point to a rs485_dev.
 * @param  *usart:  point to a USART_Dev.
 * @param  pin_re:  pin number, like PA0. @See "gpio.h"
 * @retval None
 */
void rs485_init(rs485_dev *rs485, USART_Dev *usart, PIN_Dev pin_re);

/* Send information functions ------------------------------------------------------- */
/**
 * @brief  rs485 send data function.
 * @param  *rs485:  point to a rs485_dev.
 * @param  *byte:   a byte information.
 * @retval None
 */
void rs485_write_byte(rs485_dev *rs485, const uint8_t byte);

/**
 * @brief  rs485 send data function.
 * @param  *rs485:  point to a rs485_dev.
 * @param  *buf:    point to a buffer where your data save.
 * @param  length:  the length of buffer.
 * @retval None
 */
void rs485_write_buffer(rs485_dev *rs485, const uint8_t *buf, uint32_t length);

/**
 * @brief  rs485 send data function.
 * @param  *rs485:  point to a rs485_dev.
 * @param  *str:    point to a string (end with '\0')
 * @retval None
 */
void rs485_write_string(rs485_dev *rs485, const uint8_t *str); 
    
#endif /* RS485_INIT_H */
